//
//  RightViewController.m
//  Slider_SB
//
//  Created by xalo on 16/4/13.
//  Copyright © 2016年 李海强. All rights reserved.
//

#import "RightViewController.h"
#define kWidth self.view.frame.size.width
#define kHight self.view.frame.size.height

@interface RightViewController ()

@end

@implementation RightViewController
- (IBAction)clickAction:(id)sender {

    [self openSlider];
   }

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [self.navigationController.view addGestureRecognizer:pan];
    //添加观察者模式
    [self.navigationController.view addObserver:self forKeyPath:@"center" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
   
    }
#pragma mark-KVO观察者机制
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    CGPoint center=[change[@"new"]CGPointValue];
    if (center.x<kWidth/2) {
        
        center.x=kWidth/2;
        self.navigationController.view.center=center;
    }
}

#pragma mark-平移的手势

//平移的手势
-(void)panAction:(UIPanGestureRecognizer *)pan{
    
    CGPoint touchPoint=[pan translationInView:self.navigationController.view];
    CGPoint mainCenter=self.navigationController.view.center;
    mainCenter.x+=touchPoint.x;
    if (pan.state==UIGestureRecognizerStateEnded) {
        if (self.navigationController.view.frame.origin.x<kWidth*0.6) {
            
            [self closeSlider];
        }else{
            
            [self openSlider];
                    }
        return;
}
    
    self.navigationController.view.center=mainCenter;
        [pan setTranslation:CGPointMake(0, 0) inView:self.navigationController.view];
}
#pragma mark-抽屉的打开和关闭方法
-(void)closeSlider{
    
    [UIView animateWithDuration:1 animations:^{
        CGRect frame=self.navigationController.view.frame;
        frame.origin.x=0;
        self.navigationController.view.frame=frame;
        
    } completion:^(BOOL finished) {
        
    }];

    
}

-(void)openSlider{
    
    [UIView animateWithDuration:1 animations:^{

        CGRect frame=self.navigationController.view.frame;
        frame.origin.x=kWidth*0.6;
        self.navigationController.view.frame=frame;
        
    } completion:^(BOOL finished) {
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
